package com.chunuo.gulimall.ware.service.impl;

import com.chunuo.common.constant.WareConstant;
import com.chunuo.gulimall.ware.controller.PurchaseDetailController;
import com.chunuo.gulimall.ware.entity.PurchaseDetailEntity;
import com.chunuo.gulimall.ware.service.PurchaseDetailService;
import com.chunuo.gulimall.ware.service.WareSkuService;
import com.chunuo.gulimall.ware.vo.MergeVo;
import com.chunuo.gulimall.ware.vo.PurchaseDoneVo;
import com.chunuo.gulimall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chunuo.common.utils.PageUtils;
import com.chunuo.common.utils.Query;

import com.chunuo.gulimall.ware.dao.PurchaseDao;
import com.chunuo.gulimall.ware.entity.PurchaseEntity;
import com.chunuo.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    /**
     * 采购项 添加到采购单中时，获取还没有采购的采购单（可以选择）
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<PurchaseEntity>().
                eq("status", WareConstant.PurchaseStatusEnum.CREATED.getCode()).or().
                eq("status",WareConstant.PurchaseStatusEnum.ASSIGNED.getCode());

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    //合并整单 采购项 整到采购单中
    @Transactional
    @Override
    public void WithMerge(MergeVo vo) {
        Long purchaseId = vo.getPurchaseId();
        //如果没有传采购单，则创建一个采购单
        if(purchaseId==null||purchaseId==0){
            //创建一个采购单
            PurchaseEntity purchase = new PurchaseEntity();
            purchase.setCreateTime(new Date());
            purchase.setUpdateTime(new Date());
            purchase.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchase);
            purchaseId = purchase.getId();
        }

        List<Long> items = vo.getItems();
        Long finalPurchaseId = purchaseId;
        // 映射采购项 并添加到采购单中，以及修改状态为已分配
        List<PurchaseDetailEntity> collect = items.stream().map(item -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(item);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());

        purchaseDetailService.updateBatchById(collect);

        //批量整合后，修改更新时间
        PurchaseEntity purchase = new PurchaseEntity();
        purchase.setId(purchaseId);
        purchase.setUpdateTime(new Date());
        this.updateById(purchase);

    }

    /**
     * 采购员 开始采购
     * @param ids 采购单的list id
     */
    @Transactional
    @Override
    public void received(List<Long> ids) {

        List<PurchaseEntity> collect = ids.stream().map(id -> {
            //id查找到整体数据
            PurchaseEntity purchaseEntity = this.getById(id);
            return purchaseEntity;
        }).filter(entity->{
            // 状态只能是新建 或者 已分配
            if(entity.getStatus()==WareConstant.PurchaseStatusEnum.CREATED.getCode()||
                entity.getStatus()==WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()){
                //设置为夷陵区
                entity.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
                entity.setUpdateTime(new Date());
                return true;
            }
            return false;
        }).collect(Collectors.toList());
        //批量更新采购单
        this.updateBatchById(collect);

        //遍历采购单
        collect.forEach(purchaseEntity->{
            //采购单 查询 所有的采购项
            List<PurchaseDetailEntity> purchaseIds = purchaseDetailService.findListByPurchaseDetailId(purchaseEntity.getId());
            //采购项更新状态为 正在采购
            List<PurchaseDetailEntity> purchaseDetailEntityList = purchaseIds.stream().map(entity -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(entity.getId());
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            //批量更新采购项
            purchaseDetailService.updateBatchById(purchaseDetailEntityList);
        });

    }

    @Transactional
    @Override
    public void done(PurchaseDoneVo doneVo) {
        Long id = doneVo.getId();

        List<PurchaseItemDoneVo> items = doneVo.getItems();

        boolean flag = true;
        List<PurchaseDetailEntity> updates = new ArrayList<>();
        for (PurchaseItemDoneVo item: items){
            PurchaseDetailEntity entity = new PurchaseDetailEntity();
            entity.setId(item.getItemId());
            entity.setStatus(item.getStatus());
            if(item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                //采购未能完成  异常
                flag = false;
            }else{
                //采购顺利 完成
                // 更新库存等信息
                PurchaseDetailEntity byId = purchaseDetailService.getById(item.getItemId());
                wareSkuService.updateStock(byId.getSkuId(),byId.getWareId(),byId.getSkuNum());
            }
            updates.add(entity);
        }

        purchaseDetailService.updateBatchById(updates);


        //根据采购项status决定采购单的状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag?
                WareConstant.PurchaseStatusEnum.FINISH.getCode():
                WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());

        this.updateById(purchaseEntity);

    }

}